package com.geticsen.leetcode;

import java.util.Stack;

public class Solution_394 {
    public String decodeString(String s) {
        Stack<Integer> integerStack = new Stack<>();
        Stack<String> stringStack = new Stack<>();
        int num = 0;
        for (int i = 0; i < s.length(); i++) {
            char cur = s.charAt(i);
            if ('0' <= cur && cur <= '9') {
                num = num * 10 + cur - '0';
            } else if (cur == '[') {
                integerStack.push(num);
                num = 0;
                stringStack.push( "");
            } else if (cur == ']') {
                Integer peek = integerStack.pop();
                String pop = generateString(stringStack.pop(), peek);
                stringStack.push((stringStack.empty() ? "" : stringStack.pop()) + pop);
            } else {
                stringStack.push((stringStack.empty() ? "" : stringStack.pop()) + cur);
            }
        }
        return stringStack.peek();
    }

    private String generateString(String in, int repeat) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < repeat; i++) {
            s.append(in);
        }
        return s.toString();
    }

    public static void main(String[] args) {
        Solution_394 solution_394 = new Solution_394();
        String s = solution_394.decodeString("3[z]2[2[y]pq4[2[jk]e1[f]]]ef");
        //"zzzyypqjkjkefjkjkefjkjkefjkjkefyypqjkjkefjkjkefjkjkefjkjkefef"

        System.out.println("s = " + s);
    }
}
